import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { Router } from '@angular/router';
import { HttpService } from 'src/app/service/http.service';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import {Device} from '@ionic-native/device/ngx';
import {ThemeableBrowser, ThemeableBrowserOptions} from '@ionic-native/themeable-browser/ngx';
import {TranslateService} from '@ngx-translate/core';

@Component({
    selector: 'app-doctor-home',
    templateUrl: './doctor-home.page.html',
    styleUrls: ['./doctor-home.page.scss'],
})
export class DoctorHomePage implements OnInit {
    dataList = [];
    unreadNum = 0;
    loadTimes = 0;
    stopLoad = false;
    showNone = false;
    userData: any = {};
    weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    menuHeaderStyle = {};
    isIos = 0; // 0不是ios 1是ios
    sysLang = '';

    constructor(
        private device: Device,
        private statusBar: StatusBar,
        private navCtrl: NavController,
        private router: Router,
        private httpService: HttpService,
        private translate: TranslateService,
        private themeableBrowser: ThemeableBrowser
    ) {
    }

    async ngOnInit() {
        this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
        this.statusBar.backgroundColorByHexString('#009e41');
        if (this.device.platform) {
            if (this.device.platform.toUpperCase() === 'ANDROID') {
                this.menuHeaderStyle = {'margin-top': '44px'};
                this.isIos = 0;
            } else if (this.device.platform.toUpperCase() === 'IOS') {
                this.menuHeaderStyle = {'margin-top': '44px'};
                this.isIos = 1;
            }
        }
    }

    async ionViewDidEnter() {
        await this.getOrderList('fresh', 0);
        await this.getPersonInfo();
        await this.getUnreadList();
    }

    public async toPage() {
        await this.navCtrl.navigateForward(['doctor-password'], {
            queryParams: { isForgetPassword: '1' }
        });
    }

    public async signOut() {
        await this.httpService.put()
            .setPath('/user/userLogout')
            .request();

        localStorage.removeItem('userId');
        localStorage.removeItem('userType');
        localStorage.removeItem('auth-token');
        localStorage.removeItem('redirectTo');
        await this.navCtrl.navigateRoot('/login');
    }

    public async logOut() {
        await this.httpService.put()
            .setPath('/user/userLogoff')
            .request();

        localStorage.removeItem('userId');
        localStorage.removeItem('userType');
        localStorage.removeItem('auth-token');
        localStorage.removeItem('redirectTo');
        await this.navCtrl.navigateRoot('/login');
    }

    public onHelp() {
        const helpLink = 'http://www.sincaremedicaltour.com/news_detail.php?id=437';
        const options: ThemeableBrowserOptions = {
            statusbar: {
                color: '#009e41'
            },
            toolbar: {
                height: 44,
                color: '#009e41'
            },
            title: {
                color: '#ffffff',
                staticText: 'Q&A',
                showPageTitle: true
            },
            backButton: {
                wwwImage: '/assets/icon/direction-left.png',
                wwwImagePressed: '/assets/icon/direction-left.png',
                imagePressed: 'back_pressed',
                align: 'left',
                event: 'backPressed'
            },
            backButtonCanClose: true
        };

        this.themeableBrowser.create(helpLink, '_blank', options);
    }

    public async getOrderList(aType, aLoadtimes) {
        const aOffset = aLoadtimes * 10;
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.get()
            .setPath('/order/orderBookingList')
            .setQuery({
                doctorUserId: aUserId,
                orderType: 1,
                orderBooking: 2,
                // orderAccept: 2,
                processAccept: true,
                offset: aOffset,
                limit: 10
            })
            .request();
        if (result.status === 0) {
            if (aType === 'fresh') {
                this.dataList = result.data.rows;
            } else if (aType === 'infinite') {
                for (const item of result.data.rows) {
                    this.dataList.push(item);
                }
            }
            for (const item of this.dataList) {
                item.order_time = `${item.start_time} - ${item.end_time.split(' ')[1]}`;
            }
            this.stopLoad = true;
            if (this.dataList.length === result.data.count) {
                this.showNone = true;
            }
        }
    }

    public async getUnreadList() {
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.get()
            .setPath('/order/unreadCount')
            .setQuery({
                userId: aUserId
            })
            .request();
        if (result.status === 0) {
            this.unreadNum = result.data[0].count;
        }
    }

    public async doRefresh(event) {
        this.loadTimes = 0;
        await this.getOrderList('fresh', 0);
        if (!!this.stopLoad) {
            event.target.complete();
        }
    }

    public async loadData(event) {
        this.loadTimes += 1;
        await this.getOrderList('infinite', this.loadTimes);
        if (!!this.stopLoad) {
            event.target.complete();
        }
    }

    public async clickOrder(item) {
        await this.router.navigate(['doctor-appoint-details'], {
            queryParams: {
                startTime: item.start_time,
                endTime: item.end_time,
                patientId: item.patient_user_id,
                orderId: item.id,
                orderAccept: item.order_accept,
                doctorType: item.dct_type
            }
        });
    }

    public async getPersonInfo() {
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.get()
            .setPath('/user/doctorInfo/' + aUserId)
            .request();
        if (result.status === 0) {
            this.userData = result.data;
        }
    }

    public toPrivacy() {
        this.navCtrl.navigateForward(['privacy']);
    }
}
